package com.sctvcloud.linshui.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.githang.statusbar.StatusBarCompat;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.linshui.R;
import com.sctvcloud.linshui.application.Cache;
import com.sctvcloud.linshui.base.BaseActivity;
import com.sctvcloud.linshui.im.ImInterface;
import com.sctvcloud.linshui.ui.adapter.ChatRoomMsgAdapter;
import com.sctvcloud.linshui.ui.adapter.holder.ChatRoomMsgHolder;
import com.sctvcloud.linshui.ui.utils.TitleUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jmessage.biz.httptask.task.GetEventNotificationTaskMng;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.event.ChatRoomMessageEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.ChatRoomInfo;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

/**
 * 极光IM 聊天室
 */
public class ChatRoomActivity extends BaseActivity implements ChatRoomMsgHolder.OnChatItemClickListener {
    @BindView(R.id.chat_room_title)
    protected CustomFontTextView chat_room_title;
    @BindView(R.id.chat_list)
    protected RecyclerView chatList;
    @BindView(R.id.edit_input)
    protected EditText editInput;
    @BindView(R.id.root_layout)
    protected LinearLayout rootLayout;

    private ChatRoomMsgAdapter msgAdapter;
    public static final String CHAT_ROOM_ID = "chat_room_id";
    public static final String CHAT_ROOM_TITLE = "chat_room_title";
    private List<Message> msgList = new ArrayList<>();
    private String title;
    private long roomId;
    private UserInfo imUserInfo;
    private boolean firstLoad = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        setThisImmersive(true);
        super.onCreate(savedInstanceState);
//        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white));
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        title = getIntent().getStringExtra(CHAT_ROOM_TITLE);
        roomId = getIntent().getLongExtra(CHAT_ROOM_ID, 0);
        chat_room_title.setText(title);
        imUserInfo = Cache.getInstance().getImUserInfo();
        leaveChatRoom();
        joinChatRoom();


        chatList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        chatList.setItemAnimator(new DefaultItemAnimator());
        msgAdapter = new ChatRoomMsgAdapter(this, null,this);
        chatList.setAdapter(msgAdapter);
        rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            boolean isScroll = true;
            long diff = 0;

            @Override
            public void onGlobalLayout() {
                int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
                if (heightDiff != diff) {
                    isScroll = true;
                } else {
                    isScroll = false;
                }
                diff = heightDiff;
                if (heightDiff > 200) { // 如果高度差超过100像素，就很有可能是有软键盘...
                    if (ListUtils.isListValued(msgList) && isScroll) {
                        chatList.scrollToPosition(msgList.size() - 1);
                    }
                }
            }
        });
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_chat_room);
        ButterKnife.bind(this);
    }

    /**
     * 加入聊天室
     */
    private void joinChatRoom() {
        ImInterface.getInstance().imJoinChatRoom(roomId, new RequestCallback<Conversation>() {
            @Override
            public void gotResult(int i, String s, Conversation conversation) {
                JLog.d("-----ChatRoomMessageEvent----imJoinChatRoom--------s -" + s + "----conversation =" + conversation);
                JMessageClient.registerEventReceiver(ChatRoomActivity.this);
            }
        });
    }

    /**
     * 离开聊天室
     */
    private void leaveChatRoom() {
        ImInterface.getInstance().imLeaveChateRoom(roomId, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                JLog.d("-----ChatRoomMessageEvent----imLeaveChateRoom--------s -" + s);
            }
        });
    }

    /**
     * 发送聊天室消息
     *
     * @param msgTxt
     */
    private void sendChatRoomMsg(String msgTxt) {
        // 发送聊天室消息
        Conversation conv = JMessageClient.getChatRoomConversation(roomId);
        if (null == conv) {
            conv = Conversation.createChatRoomConversation(roomId);
        }
        final Message msg = conv.createSendTextMessage(msgTxt);//实际聊天室可以支持所有类型的消息发送，demo为了简便，仅仅实现了文本类型的消息发送，其他的消息类型参考消息发送相关文档
        msg.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage) {
                if (0 == responseCode) {
                    //发送成功
                    JLog.d("ChatRoomMessageEvent ---- send success  -");
                    msgList.add(msg);
                    msgAdapter.setData(msgList);
                    if (ListUtils.isListValued(msgList)) {
                        chatList.scrollToPosition(msgList.size() - 1);
                    }
                } else {
                    //发送失败
                    toast("发送失败");
                    JLog.d("ChatRoomMessageEvent ---- send faild  -");
                }
                firstLoad = false;
            }
        });
        JMessageClient.sendMessage(msg);

    }

    // 接收聊天室消息
    public void onEventMainThread(ChatRoomMessageEvent event) {
        List<Message> msgs = event.getMessages();
        JLog.d("ChatRoomMessageEvent ---- msgs.size()  -" + msgs.size());
        for (Message msg : msgs) {
            //这个页面仅仅展示聊天室会话的消息
            msgList.add(msg);
        }
        if (firstLoad) {
            showProgress("正在加载...");
        }
        msgAdapter.setData(msgList);
        if (ListUtils.isListValued(msgList)) {
            chatList.scrollToPosition(msgList.size() - 1);
        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                closeProgress();
                if (null != msgAdapter) {
                    msgAdapter.notifyDataSetChanged();
                }
                firstLoad = false;
            }
        }, 500);

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                String sendMsg = editInput.getText().toString().trim();
                if (TextUtils.isEmpty(sendMsg)) {
                    toast("输入不能为空");
                    return false;
                }
                sendChatRoomMsg(sendMsg);
                editInput.setText("");
            }
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        leaveChatRoom();
        JMessageClient.unRegisterEventReceiver(this);
    }

    @OnClick({R.id.btn_back})
    protected void OnClick(View view) {
        if (view.getId() == R.id.btn_back) {
            finish();
        }
    }

    @Override
    public void onItemClick(Message message) {
        InputMethodManager imm = (InputMethodManager) editInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(editInput.getApplicationWindowToken(), 0);
        }
    }
}
